# -*- coding: utf-8 -*-
# createTime: 2018/12/28 13:50

from django.contrib.auth.backends import ModelBackend, get_user_model
from django.db.models import Q
User = get_user_model()


class DoubleMethodBackend(ModelBackend):
    """
    Username/Email 都可验证
    """
    def authenticate(self, request, password=None, **credentials):
        login_field = credentials.get('username', credentials.get('email'))
        if login_field:
            try:
                user = User.objects.get(Q(username=login_field)|Q(email=login_field))
            except User.DoesNotExist:
                User().set_password(password)
            else:
                if user.check_password(password) and self.user_can_authenticate(user):
                    return user

